package com.qiantu.phone.ui.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.interpolator.view.animation.FastOutSlowInInterpolator;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleOwner;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hjq.base.BaseAdapter;
import com.hjq.http.listener.HttpCallback;
import com.hjq.toast.ToastUtils;
import com.qiantu.api.db.LLControllerDBManager;
import com.qiantu.api.db.LLDeviceDBManager;
import com.qiantu.api.entity.ControllerBean;
import com.qiantu.api.entity.DeviceBean;
import com.qiantu.api.entity.KGXcollectionData;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.phone.R;
import com.qiantu.phone.action.StatusAction;
import com.qiantu.phone.aop.Log;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.event.DeviceItemChangeEvent;
import com.qiantu.phone.event.DeviceListChangeEvent;
import com.qiantu.phone.event.RefreshDeviceListEvent;
import com.qiantu.phone.glide.GlideApp;
import com.qiantu.phone.ui.adapter.EnviromentScrollAdapter;
import com.qiantu.phone.ui.adapter.LoadDeviceAdapter;
import com.qiantu.phone.ui.uiutil.LLDeviceUtil;
import com.qiantu.phone.widget.StatusLayout;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * time   : 2021/12/22
 */
public final class KGXControllerDeviceAcitvity extends AppActivity implements OnRefreshLoadMoreListener, StatusAction {
    private int pageIndex = 1;
    private int pageSize = 10;
    //1初始化  2刷新  3加载更多
    private int requestType = 1;
    private StatusLayout mStatusLayout;
    private SmartRefreshLayout smartRefreshLayout;
    private ImageView iconController;
    private TextView tvControllerName;
    private TextView tvControllerId;
    private TextView tvControllerStatus;
    private  View btnSetting;
    private RecyclerView enviromentRecyclerView;
    private RecyclerView loadDeviceRecyclerView;
    private View deviceViewContainer;

    private EnviromentScrollAdapter mEnviromentAdapter;
    private LoadDeviceAdapter mLoadDeviceAdapter;

    private Fragment deviceFragment;
    private FragmentManager mFragmentManager;
    private TranslateAnimation mShowTranslateAnimation;
    private TranslateAnimation mHideTranslateAnimation;
    private KGXcollectionData collectionData;

    private List<KGXcollectionData> deviceCollects;

    @Log
    public static void start(Context context, KGXcollectionData collectionData,List<KGXcollectionData> deviceCollects) {
        Intent intent = new Intent(context, KGXControllerDeviceAcitvity.class);
        intent.putExtra("collectionData", collectionData);
        intent.putExtra("deviceCollects", (Serializable) deviceCollects);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_kgx_controller_device;
    }

    @Override
    protected void initView() {
        EventBus.getDefault().register(this);
        collectionData = getSerializable("collectionData");
        deviceCollects =
                (List<KGXcollectionData>) getIntent().getSerializableExtra("deviceCollects");
        mStatusLayout = findViewById(R.id.status_layout);
        smartRefreshLayout = findViewById(R.id.smart_refresh_layout);
        iconController = findViewById(R.id.icon_controller);
        tvControllerName = findViewById(R.id.tv_controller_name);
        tvControllerId = findViewById(R.id.tv_controller_id);
        tvControllerStatus = findViewById(R.id.tv_controller_status);
        tvControllerStatus.setVisibility(View.GONE);
        btnSetting = findViewById(R.id.btn_setting);
        enviromentRecyclerView = findViewById(R.id.environment_recycler_view);
        loadDeviceRecyclerView = findViewById(R.id.load_device_recycler_view);
        deviceViewContainer = findViewById(R.id.device_view_container);
        smartRefreshLayout.setEnableRefresh(false);
        smartRefreshLayout.setEnableLoadMore(false);
        smartRefreshLayout.setOnRefreshLoadMoreListener(this);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        linearLayoutManager.setOrientation(RecyclerView.HORIZONTAL);
        mEnviromentAdapter = new EnviromentScrollAdapter(getContext());
        mEnviromentAdapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerView recyclerView, View itemView, int position) {
                DeviceBean device = mEnviromentAdapter.getData().get(position);
                DeviceSettingActivity.start(getContext(), device.getDeviceSerialNo(), false);
            }
        });
        enviromentRecyclerView.setAdapter(mEnviromentAdapter);
        enviromentRecyclerView.setLayoutManager(linearLayoutManager);

        GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(), 2);
        loadDeviceRecyclerView.setLayoutManager(gridLayoutManager);
        mLoadDeviceAdapter = new LoadDeviceAdapter(this);
        //整个cell的操作
        mLoadDeviceAdapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerView recyclerView, View itemView, int position) {
                DeviceBean device = mLoadDeviceAdapter.getData().get(position);
                if(device.getMainControlType().equals("0")){
                    DeviceBean mDevice = mLoadDeviceAdapter.getData().get(position);
                    if(mDevice.getType().equals("curtain")){
                        Boolean isOn = mDevice.getStrokePercentage() > 50;
                        curtainOperation(position,isOn);
                    }else{
                        boolean isOn = mDevice.getStateData().getStatus().getPower() == 1;
                        operaterDevice(position,!isOn);
                    }
                }else{
                    if(device.getHasControlCard() == 1){
                        showDeviceView(LLDeviceUtil.getDeviceDetailPage(device, 1));
                    }else{
                        DeviceSettingActivity.start(getContext(), device.getDeviceSerialNo());
                    }
                }
            }
        });
        //点点点的操作
        mLoadDeviceAdapter.setOnChildClickListener(R.id.btn_device_operate, new BaseAdapter.OnChildClickListener() {
            @Override
            public void onChildClick(RecyclerView recyclerView, View childView, int position) {
                DeviceBean device = mLoadDeviceAdapter.getData().get(position);
                if(device.getHasControlCard() == 1){
                    showDeviceView(LLDeviceUtil.getDeviceDetailPage(device, 1));
                }else{
                    if(AppApplication.getInstance().getCurHouseInfo().getRoleType() != 2) {
                        DeviceSettingActivity.start(getContext(), device.getDeviceSerialNo());
                    }
                }
            }
        });
        loadDeviceRecyclerView.setAdapter(mLoadDeviceAdapter);
        btnSetting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                KGXControllerSettingActivity.start(getContext(), collectionData,deviceCollects);
            }
        });
    }

    @Override
    protected void initData() {

        setTitle("负载");
        GlideApp.with(iconController).load(collectionData.getImageUrl()).into(iconController);
        tvControllerName.setText(collectionData.getName());
        tvControllerId.setText(collectionData.getProtocolAddress());
        getLoadDevices();
    }

    private void getLoadDevices(){
        List<DeviceBean> data = LLDeviceDBManager.getInstance(getContext()).getDeviceByControllerSerial4KGXEnable(collectionData.getControllerSerialNo(),collectionData.getDeviceCollectSerialNo());
        mLoadDeviceAdapter.setData(data);
        enviromentRecyclerView.setVisibility(View.GONE);
    }

    public void showDeviceView(Fragment fragment) {
        if (mFragmentManager == null) {
            mFragmentManager = getSupportFragmentManager();
        }
        FragmentTransaction transaction = mFragmentManager.beginTransaction();
        if (deviceFragment != null && deviceFragment.isAdded()) {
            transaction.remove(deviceFragment);
        }
        deviceFragment = fragment;
        transaction.add(R.id.device_view_container, fragment, "device_view");
        // 事务提交
        transaction.commitNowAllowingStateLoss();
        deviceViewContainer.setVisibility(View.VISIBLE);
        ViewGroup contentView = deviceViewContainer.findViewById(R.id.content_view);
        if (contentView.getChildCount() > 0) {
            View deviceView = contentView.getChildAt(0);
            showTopBottomAnimation(deviceView);
//            showScaleAnimation(clickView, deviceView);
        }
    }

    public boolean hideDeviceView() {
        if (mFragmentManager == null) {
            mFragmentManager = getSupportFragmentManager();
        }
        deviceFragment = mFragmentManager.findFragmentByTag("device_view");
        if (deviceFragment != null) {
            ViewGroup contentView = deviceViewContainer.findViewById(R.id.content_view);
            if (contentView.getChildCount() > 0) {
                View deviceView = contentView.getChildAt(0);
                hideTopBottomAnimation(deviceView);
                return true;
            }
        }
        return false;
    }

    private void showTopBottomAnimation(View deviceView) {
        if (mShowTranslateAnimation == null) {
            mShowTranslateAnimation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 1, Animation.RELATIVE_TO_SELF, 0);
            mShowTranslateAnimation.setDuration(300);//跑一个周期所用时长
            mShowTranslateAnimation.setInterpolator(new FastOutSlowInInterpolator());
        }
        deviceView.setVisibility(View.VISIBLE);
        deviceView.startAnimation(mShowTranslateAnimation);
    }

    private void hideTopBottomAnimation(View deviceView) {
        if (mHideTranslateAnimation == null) {
            mHideTranslateAnimation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 1);
            mHideTranslateAnimation.setDuration(300);//跑一个周期所用时长
            mHideTranslateAnimation.setInterpolator(new FastOutSlowInInterpolator());
            mHideTranslateAnimation.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {

                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    FragmentTransaction transaction = mFragmentManager.beginTransaction();
                    if (deviceFragment != null && deviceFragment.isAdded()) {
                        transaction.remove(deviceFragment);
                    }
                    // 事务提交
                    transaction.commitNowAllowingStateLoss();
                    deviceViewContainer.setVisibility(View.GONE);
                }

                @Override
                public void onAnimationRepeat(Animation animation) {

                }
            });
        }
        deviceView.startAnimation(mHideTranslateAnimation);
    }

    @Override
    public void onBackPressed() {
        if (hideDeviceView()) {
            return;
        }
        super.onBackPressed();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRefreshDeviceListEvent(RefreshDeviceListEvent event) {
        getLoadDevices();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onDeviceChangeEvent(DeviceItemChangeEvent event) {
        DeviceBean device = LLDeviceDBManager.getInstance(getContext()).getDeviceBySerialNo(event.deviceSerialNo);
        if(device != null){
            mLoadDeviceAdapter.update(device);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onDeviceListChangeEvent(DeviceListChangeEvent event) {
        //判断房间是否跟设备所在房间才更新
        if (event.deviceSerialNos != null && event.deviceSerialNos.size() > 0) {
            List<DeviceBean> devices = LLDeviceDBManager.getInstance(getContext()).getAvailableDevicesByDeviceSerialNos(event.deviceSerialNos);
            //查询后，没有设备关闭设备弹框
            if(devices == null || devices.size() == 0){
//                hideDeviceView();
            }else{
                mLoadDeviceAdapter.update(devices);
            }
        }
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Override
    public void onResume() {
        initData();
        super.onResume();
    }

    @Override
    public StatusLayout getStatusLayout() {
        return mStatusLayout;
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        requestType = 3;
        pageIndex = (int) Math.ceil(((float) mLoadDeviceAdapter.getData().size() / pageSize)) + 1;
        getLoadDevices();
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        requestType = 2;
        pageIndex = 1;
        getLoadDevices();
    }

    private void operaterDevice(int position,boolean isOn){
        DeviceBean deviceBean = mLoadDeviceAdapter.getData().get(position);
        Map<String, Object> option = new HashMap<>();
        option.put(LLDeviceUtil.POWER, isOn ? 1 : 0);
        Map<String, Object> status = new HashMap<>();
        status.put(LLDeviceUtil.STATUS, option);

        HttpCallback<HttpData<Void>> callback = new HttpCallback<HttpData<Void>>(null){
            @Override
            public void onStart(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity) {
                    ((AppActivity) getContext()).showDialog("执行中...");
                }
            }

            @Override
            public void onSucceed(HttpData<Void> result) {
                mLoadDeviceAdapter.getData().get(position).getStateData().getStatus().setPower(isOn ? 1 : 0);
                mLoadDeviceAdapter.notifyItemChanged(position);
//                ToastUtils.show("执行成功");
            }

            @Override
            public void onFail(Exception e) {
                if(getContext() != null && getContext() instanceof AppActivity) {
                    ToastUtils.show(R.string.exec_failure);
                }
            }

            @Override
            public void onEnd(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity) {
                    ((AppActivity) getContext()).hideDialog();
                }
            }
        };
        if(deviceBean.getDeviceGroup() == 0){
            LLHttpManager.operationDevice((LifecycleOwner) getContext(), deviceBean.getDeviceSerialNo(), status, callback);
        }else {
            LLHttpManager.operationDeviceGroup((LifecycleOwner) getContext(), deviceBean.getDeviceSerialNo(), status, callback);
        }
    }

    protected void curtainOperation(int position,boolean isOn){
        DeviceBean deviceBean = mLoadDeviceAdapter.getData().get(position);
        Map<String, Object> option = new HashMap<>();
        option.put(LLDeviceUtil.STROKE_PERCENTAGE, isOn ? 0 : 100);
        Map<String, Object> status = new HashMap<>();
        status.put(LLDeviceUtil.STATUS, option);
        HttpCallback<HttpData<Void>> callback =  new HttpCallback<HttpData<Void>>(null) {
            @Override
            public void onStart(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity) {
                    ((AppActivity) getContext()).showDialog("执行中...");
                }
            }

            @Override
            public void onSucceed(HttpData<Void> result) {
                mLoadDeviceAdapter.getData().get(position).getStateData().getStatus().setStrokepercentage(isOn ? 0 : 100);
                mLoadDeviceAdapter.notifyItemChanged(position);
            }

            @Override
            public void onFail(Exception e) {
                if(getContext() != null && getContext() instanceof AppActivity) {
                    ToastUtils.show(R.string.exec_failure);
                }
            }

            @Override
            public void onEnd(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity) {
                    ((AppActivity) getContext()).hideDialog();
                }
            }
        };
        LLHttpManager.operationDevice((LifecycleOwner) getContext(), deviceBean.getDeviceSerialNo(), status, callback);
    }
}